/*
 * Copyright (C) 2018 Sergej Shafarenka, www.halfbit.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package magnet.processor.registry;

import com.squareup.javapoet.*;
import magnet.internal.Generated;
import magnet.processor.instances.generator.CodeWriter;
import magnet.processor.registry.instances.InstanceIndexGenerator;

import javax.lang.model.element.Modifier;

import static magnet.processor.registry.RegistryProcessor.REGISTRY_CLASS_NAME;

class RegistryGenerator {

    private final String INSTANCE_MANAGER = "instanceManager";
    private final String INSTANCE_MANAGER_NAME = "MagnetInstanceManager";
    private final String INSTANCE_MANAGER_PACKAGE = "magnet.internal";

    private InstanceIndexGenerator instanceIndexGenerator = new InstanceIndexGenerator();

    public CodeWriter generate(Model.Registry registry) {

        CodeBlock instanceFactoriesIndex = instanceIndexGenerator.generate(registry);
        ClassName registryClassName = ClassName.bestGuess(REGISTRY_CLASS_NAME);
        ClassName factoryRegistryClassName = ClassName.get(INSTANCE_MANAGER_PACKAGE, INSTANCE_MANAGER_NAME);

        TypeSpec typeSpec = TypeSpec
                .classBuilder(registryClassName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addAnnotation(Generated.class)
                .addMethod(MethodSpec
                        .methodBuilder("register")
                        .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                        .addParameter(ParameterSpec.builder(factoryRegistryClassName, INSTANCE_MANAGER).build())
                        .addCode(instanceFactoriesIndex)
                        .addStatement("$L.register(factories, index)", INSTANCE_MANAGER)
                        .build())
                .build();

        String packageName = registryClassName.packageName();
        return new CodeWriter(packageName, typeSpec);
    }
}
